import { defineStore } from 'pinia'
import { ref } from 'vue'

import { pphService } from '../services/pphService'

export const useGlobalStore = defineStore('global', () => {
  // 全局状态
  const isLoading = ref(false)
  const loadingText = ref('加载中...')
  const systemHealth = ref<any>(null)
  const currentUser = ref<string>('操作员')

  // 系统信息
  const systemInfo = ref({
    name: 'PPH生产效率系统',
    version: '1.0.0',
    ports: {
      frontend: 3010,
      backend: 3011
    }
  })

  // 方法
  function setLoading(loading: boolean, text = '加载中...') {
    isLoading.value = loading
    loadingText.value = text
  }

  async function checkSystemHealth() {
    try {
      setLoading(true, '检查系统状态...')
      const healthy = await pphService.healthCheck()
      systemHealth.value = {
        status: healthy ? 'healthy' : 'unhealthy',
        lastCheck: new Date().toISOString()
      }
      return healthy
    } catch (error) {
      console.error('系统健康检查失败:', error)
      const msg = (error as any)?.message || String(error)
      systemHealth.value = {
        status: 'error',
        lastCheck: new Date().toISOString(),
        error: msg
      }
      return false
    } finally {
      setLoading(false)
    }
  }

  function showSuccess(message: string) {
    console.log(`✅ ${message}`)
  }

  function showError(message: string) {
    console.error(`❌ ${message}`)
  }

  return {
    // 状态
    isLoading,
    loadingText,
    systemHealth,
    currentUser,
    systemInfo,
    
    // 方法
    setLoading,
    checkSystemHealth,
    showSuccess,
    showError
  }
})
